package com.me.tags;

import com.me.annotation.FieldAttr;
import com.me.enums.FieldType;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

public class InputTag extends SimpleTagSupport {
	private String jsp_for;
	private String jsp_class;

	@Override
	public void doTag() throws JspException, IOException {
		PageContext page = ((PageContext) this.getJspContext());
		ServletRequest req = page.getRequest();
		Object model = req.getAttribute("Model");
		JspWriter out = page.getOut();

		FieldAttr attr = null;
		try {
			attr = model.getClass().getDeclaredField(jsp_for).getAnnotation(FieldAttr.class);
			if (attr != null) {
				FieldType type = (FieldType) attr.getClass().getMethod("type").invoke(attr);
				Boolean required = (Boolean) attr.getClass().getMethod("required").invoke(attr);
				Object value = model.getClass().getMethod(String.format("get%s", jsp_for.substring(0, 1).toUpperCase() + jsp_for.substring(1))).invoke(model);
				out.print(
						String.format("<input type='%1$s' id='%2$s' name='%2$s' %3$s %4$s %5$s />",
							type,
							jsp_for,
							jsp_class == null ? "" : String.format("class='%s'",jsp_class),
							value == null || value == "" ? "" : String.format("value='%s'",value),
							required ? "required='required'" : ""
						)
				);
			}
		} catch (NoSuchFieldException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	public void setJsp_for(String jsp_for) {
		this.jsp_for = jsp_for;
	}

	public void setJsp_class(String jsp_class) {
		this.jsp_class = jsp_class;
	}
}
